package com.xspace.android.imcommon.http;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.imcommon.entity.FindFriendsBean;
import com.xspace.android.imcommon.utils.ImConstants;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;

public class FetchFriendsTask implements NetworkListener {
	private String uuid;
	private String contacts;
	private IFindFriendsResult requestResult;
	public FetchFriendsTask(String uuid, String contacts, IFindFriendsResult requestResult) {
		this.uuid = uuid;
		this.contacts = contacts;
		this.requestResult = requestResult;
	}

	@Override
	public void action(int actionCode, Object object) {
		switch (actionCode) {
		case NetworkListener.RECEIVE_STREAM:
			try {
				String result = AppUtils.parser((InputStream) object);
				LogUtils.i("fetch friends response : %s"+ result);
				parserContactList(result);
			} catch (Exception e) {
				this.requestResult.requestResult(null);
				LogUtils.i("FetchFriendsTask"+ e+ "");
			}
			break;
		case NetworkListener.REQUEST_TIMEOUT:
		case NetworkListener.STREM_EXCEPTION:
		case NetworkListener.APN_NOTEXIST:
			this.requestResult.requestResult(null);
			break;
		}
	}

	/**
	 * 解析网络联系人列表
	 * 
	 * @param result
	 * @throws Exception
	 */
	private void parserContactList(String result) throws Exception {
		JSONObject json = new JSONObject(result);
		ArrayList<FindFriendsBean> friendLise=new ArrayList<FindFriendsBean>();
		int code = json.getInt("code");
		if (code == 0) {
			try {
				String returnRes = json.getString("userList");
				Gson mGson=new Gson();
				friendLise = (mGson.fromJson(returnRes,
						new TypeToken<ArrayList<FindFriendsBean>>() {
						}.getType()));

			} catch (Exception e) {
				e.printStackTrace();

			}
			this.requestResult.requestResult(friendLise);
		} else if (code == 1) {
			this.requestResult.requestResult(null);
		} else {
			this.requestResult.requestResult(null);
		}
	}

	/**
	 * 发送获取网络联系人请求
	 */
	public void sendFetchFriendsRequest() {
		ConnectorImpl conn = new ConnectorImpl(
				ImConstants.getFriendUrl(), buildFetchFriendsRequest(),
				this, ConnectorImpl.POST);
		ThreadPoolWrap.getThreadPool().executeTask(conn);
	}

	// 构造获取好友请求
	private String buildFetchFriendsRequest() {
		JSONObject json = new JSONObject();
		try {
			json.put("uuid", uuid.trim());
			json.put("contacts", contacts.replaceAll(" ", ""));
		} catch (JSONException e) {
			LogUtils.d("FetchFriendsTask"+e.getMessage()+
					"buildFetchFriendsRequest error");
		}
		return json.toString();
	}

}
